<script setup lang='ts'>
import {ref, reactive, PropType, onBeforeMount} from 'vue'
import { ElMessage, FormRules} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import {
  HealthGuideFormInfor, HealthGuideScanInfor,
  getHealthScanList, saveHealthScanInfor
} from '@/api/physicalExaminationManager/healthGuide'

import dDialog from '@/components/dDialog/dDialog.vue'

import operation from '@/components//dTable/components/operation.vue'
import {HeaderData, Operation as Opr, RowOperbuttons} from '@/components/dTable/dTable'
import dTable from '@/components/dTable/dTable.vue'
import {ColorRed, ColorTheme} from '@/api/config'

//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  //数据
  healthGuideData:{
    type:Object as PropType<HealthGuideFormInfor>,
    required:true
  }
})

const emits = defineEmits(['close'])

//信息
const healthGuideFormData:HealthGuideFormInfor = reactive(props.healthGuideData)

// 显示加载状态
const showSaveLoading = ref(false)

//表单清除控制
// const resetFieldsFlag = ref(false)

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  // resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

// 表格数据
const formData = ref<{tableData:Array<HealthGuideScanInfor>}>({tableData:[]})
// 表头数据
const tableHeaderData = ref<Array<HeaderData>>([
  {prop: 'healthValue', label: '健康内容', columnType: 'slot', 'min-width': '100'},
  {prop: 'oper', label: '操作', columnType: 'slot', 'width': '80'}
])

// 删除操作按钮数据
const operationDataDelete: Array<Opr> = [{code: 'delete', label: '删除', iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}}]
// 新增操作按钮数据
const operationDataAdd: Array<Opr> = [{code: 'add', label: '添加', iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}}]

//添加数据
const baseAdd = {
  healthValue: '',
  healthGuideId: healthGuideFormData.id, // 默认添加健教指导id
  oper: [],
  id:undefined
}

//添加展示按钮
const showButton = (dataList:Array<HealthGuideScanInfor>) => {
  const returnList:Array<HealthGuideScanInfor & RowOperbuttons> = []
  if (!dataList.length) {
    const newAdd = JSON.parse(JSON.stringify(baseAdd))
    dataList.push(newAdd)
  }
  dataList.map((item, index) => {
    returnList.push({...item, oper:index === (dataList.length - 1) ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })

  return returnList
}

// 添加事件
const onAdd = () => {
  const addData = JSON.parse(JSON.stringify(baseAdd))
  formData.value.tableData.push(addData)
  formData.value.tableData = showButton(formData.value.tableData)
}

// 删除事件
const onRemove = (index: number) => {
  formData.value.tableData.splice(index, 1)
  formData.value.tableData = showButton(formData.value.tableData)
}

// 操作栏点击
const onErtion = (code, row) => {
  if (code === 'delete') {
    onRemove(formData.value.tableData.indexOf(row))
  } else if (code === 'add') {
    onAdd()
  }
}


const getHealthScanListData = () => {
  if (healthGuideFormData.id) {
    getHealthScanList(healthGuideFormData.id).then(res => {
      const {data} = res.data
      // formData.value.tableData = data
      formData.value.tableData = showButton(data)
    })
  }
}


const formRef = ref()
// 弹窗保存
const onConfirmSelete = () => {
  formRef.value.validate(valid => {
    if (valid && healthGuideFormData.id) {
      saveHealthScanInfor(healthGuideFormData.id, formData.value.tableData).then(() => {
        emits('close')
      })
    }
  })
}

// 表单规则
const rules = reactive<FormRules>({
  healthValue:[
    {required:true, message:'请填写有效的健康内容', trigger:['change', 'blur']},
    {message:'长度应不超过500个字符', max:500, trigger: ['change', 'blur']}
  ]
})

onBeforeMount(() => {
  getHealthScanListData()
})

</script>

<template>
  <d-dialog
    title="配置健教内容"
    custom-class="edit"
    width="600px"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirmSelete"
    @close="onClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" :inline-message="false">
      <div :style="{height:'300px'}">
        <d-table
          ref="main"
          class="guide-table"
          style="min-height: 300px"
          :table-data="formData.tableData"
          :table-header-data="tableHeaderData"
        >
          <template #healthValue="scope">
            <el-form-item :prop="`tableData[${scope.index}].healthValue`" :rules="rules['healthValue']">
              <el-input v-model="scope.row['healthValue']" />
            </el-form-item>
          </template>
          <template #oper="scope">
            <operation
              :row="scope.row"
              :col="scope.item"
              @opertion-click="onErtion"
            />
          </template>
        </d-table>
      </div>
    </el-form>
  </d-dialog>
</template>

<style scoped lang="less">
.guide-table{
  :deep(.el-table__cell){
    padding-top: 0;
    padding-bottom: 0;
  }
  :deep(.cell){
    padding-top: 15px;
    padding-bottom: 15px;
  }
}
</style>